<?php

namespace delayQueue;

class DelayQueue
{
    protected $redis = null;
    protected $key = 'redis_plan';

    public function __construct($key = '')
    {
        if ($key) $this->key = $key;

        $this->redis = new \Redis();
        $config = [
            'host' => '127.0.0.1',
            'port' => 6379,
            'auth' => '',
            'timeout' => 60,
        ];
        $this->redis->connect($config['host'], $config['port'], $config['timeout']);
        $this->redis->auth($config['auth']);
    }

    public function delTask($value)
    {
        return $this->redis->zRem($this->key, $value);
    }

    public function getTask()
    {
        //获取任务，以0和当前时间为区间，返回一条记录
        return $this->redis->zRangeByScore($this->key, 0, time(), ['limit' => [0, 10]]);
    }

    public function addTask($name, $time, $data)
    {
        //添加任务，以时间作为score，对任务队列按时间从小到大排序
        return $this->redis->zAdd(
            $this->key,
            $time,
            json_encode(
                [
                    'task_name' => $name,
                    'task_time' => $time,
                    'task_params' => $data,
                ], JSON_UNESCAPED_UNICODE
            )
        );
    }

}